﻿<%@ WebHandler Language="C#" Class="Upload" %>

/**
 * KindEditor ASP.NET
 *
 * 本ASP.NET程序是演示程序，建议不要直接在实际项目中使用。
 * 如果您确定直接使用本程序，使用之前请仔细确认相关安全设置。
 *
 */

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Drawing;
using System.Globalization;
using LitJson;
using System.Web.SessionState;

public class Upload : IHttpHandler, IRequiresSessionState
{
    private HttpContext context;


    public void ProcessRequest(HttpContext context)
    {
        if (HttpContext.Current.Session[EnumKeys.SessionKey.USER] == null) return;

        String webFolderUrl = "/attached"; //浏览器访问此文件的URL地址
        //定义允许上传的文件扩展名
        String fileTypes = "txt,gif,jpg,jpeg,png,bmp,docx,doc,xls,xlsx,zip,rar,pdf,swf,ppt,pptx,ppsx,wrf,wmv,flv,avi";
        String imageTypes = "jpg,png,bmp";
        
        //最大文件大小
        int maxSize = 300 * 1024 * 1024; //300M
        this.context = context;

        HttpPostedFile imgFile = context.Request.Files["imgFile"];
        String uploadPath = Webapp.StringUtil.CutBadSqlInfo(Webapp.StringUtil.GetNullToString(context.Request["path"]));

        if (imgFile == null)
        {
            showError("请选择文件。");
        }

        string phsicPath = HttpContext.Current.Server.MapPath("~/") + "attached";// Maticsoft.Common.ConfigHelper.GetConfigString("defaultAttachedDirectory");

        //如果参数指定path,就将目录转向attached下的指定path
        if (uploadPath != "")
        {
            if (uploadPath.IndexOf("/") < 0)
            {
                uploadPath = "/" + uploadPath;
            }
            uploadPath = uploadPath.TrimEnd('/');
            phsicPath += uploadPath;
            webFolderUrl += uploadPath;
        }
        if (!Directory.Exists(phsicPath))
        {
            showError("上传目录不存在。");
        }

        String fileName = imgFile.FileName;
        String fileExt = Path.GetExtension(fileName).ToLower();
        ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));
        ArrayList imageTypeList = ArrayList.Adapter(imageTypes.Split(','));

        if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
        {
            showError("上传文件大小超过限制。");
        }

        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
        {
            showError("上传文件扩展名是不允许的扩展名。");
        }

        String ymd = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo);
        phsicPath += "/" + ymd + "/";
        webFolderUrl += "/" + ymd + "/";
        if (!Directory.Exists(phsicPath))
        {
            Directory.CreateDirectory(phsicPath);
        }

        String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
        String filePath = phsicPath + newFileName + fileExt;
        string thumbFilePath = phsicPath + "s_" + newFileName + fileExt;
        imgFile.SaveAs(filePath);
     
        //生成缩略图
        imgFile.SaveAs(thumbFilePath);
        if ((!String.IsNullOrEmpty(fileExt)) && (Array.IndexOf(imageTypes.Split(','), fileExt.Substring(1).ToLower()) > -1))
        {
            PicSized(filePath, thumbFilePath, 80, 100, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        
        String returnFileUrl = webFolderUrl + newFileName + fileExt;
        String returnThumbUrl = webFolderUrl + "s_"+ newFileName + fileExt;
        
        Hashtable hash = new Hashtable();
        hash["error"] = 0;
        hash["url"] = returnFileUrl;
        hash["min"] = returnThumbUrl;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    private void showError(string message)
    {
        Hashtable hash = new Hashtable();
        hash["error"] = 1;
        hash["message"] = message;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

    public void PicSized(string picPath, string reSizePicPath, int toWidth,int toHeight, System.Drawing.Imaging.ImageFormat format)
    {
        Bitmap originBmp = new Bitmap(picPath);
        int w = toWidth;// originBmp.Width* iSize;
        int h = toHeight;// originBmp.Height* iSize;
        Bitmap resizedBmp = new Bitmap(w, h);
        Graphics g = Graphics.FromImage(resizedBmp);
        //设置高质量插值法   
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        //设置高质量,低速度呈现平滑程度   
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        //消除锯齿 
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.DrawImage(originBmp, new Rectangle(0, 0, w, h), new Rectangle(0, 0, originBmp.Width, originBmp.Height), GraphicsUnit.Pixel);
        resizedBmp.Save(reSizePicPath, format);
        g.Dispose();
        resizedBmp.Dispose();
        originBmp.Dispose();
    }
}
